package com;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class IStudentImpl implements IStudent {
	
	private static  String driver = "";
	private static  String url = "";
	private static  String name = "";
	private static  String password = "";
	private static Connection conn = null;
	private static Map<String,String> methodMap = new HashMap<String,String>();
	static{
		
		try {
			SAXBuilder sax = new SAXBuilder();
			Document doc = sax.build("src/globalconfig.xml"); 
			Element root = doc.getRootElement();
			Element connetionE  = root.getChild("dbconncetion");
			List propertyE = connetionE.getChildren();
			for(int i =0 ;i<propertyE.size();i++){
				Element el = (Element)propertyE.get(i);
				if(el.getAttributeValue("id").equals("driver")){
					driver = el.getAttributeValue("value");
				}else if(el.getAttributeValue("id").equals("url")){
					url = el.getAttributeValue("value");
				}else if(el.getAttributeValue("id").equals("name")){
					name = el.getAttributeValue("value");
				}else if(el.getAttributeValue("id").equals("password")){
					password = el.getAttributeValue("value");
				} 
			}
			List beanE = root.getChildren("bean");
			for(int i =0; i<beanE.size();i++){
				Element el = (Element)beanE.get(i);
				System.out.println(el.getAttributeValue("file"));
				Document dd = sax.build(el.getAttributeValue("file")); 
				Element rr = dd.getRootElement();
				System.out.println(rr.getName());
				List sqlMap = rr.getChildren();
				for(int j =0;j<sqlMap.size();j++){
					Element ee = (Element)sqlMap.get(j);
					System.out.println(ee.getAttributeValue("id"));
					System.out.println(ee.getText());
					methodMap.put(ee.getAttributeValue("id"), ee.getText());
				}
			}
			
//			1.加载驱动程序
            Class.forName(driver);
            //2. 获得数据库连接
            conn = DriverManager.getConnection(url, name, password);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	public static void main(String[] args) {
		try {
			
			IStudent is = new IStudentImpl();
			//is.deleteStudentById("deleteStudentById", "1");
			Student s= new Student();
			/*s.setId("1");
			s.setAge("26");
			s.setName("tom");
			s.setPhonenum("110");
			is.insertStudent("insertStudent", s);
			*/
			/*List list = new ArrayList();
			list =	is.selectStudentById("selectStudentById", "1");
			s = (Student)list.get(0);
			System.out.println(s.getName());*/
			s.setId("1");
			s.setAge("264");
			s.setName("tombb");
			s.setPhonenum("110");
			is.updateStudent("updateStudent", s);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void deleteStudentById(String methodname,String id) {
		
	  try {
		  
		  String sql = methodMap.get(methodname);
		  String pattern = "\\$\\{[a-zA-Z]+\\}";
//		 创建 Pattern 对象
		  Pattern r = Pattern.compile(pattern);
		  // 现在创建 matcher 对象
		  Matcher m = r.matcher(sql);
		  while (m.find()) {
			  System.out.println("Found value: " + m.group(0) );
			  sql = sql.replace(m.group(0), "?");
			  
		  }
		  System.out.println("ss="+sql);
		  PreparedStatement pst = conn.prepareStatement(sql);
		  pst.setString(1, id);
		  int dd= pst.executeUpdate();
		  System.out.println("dd="+dd);
		  pst.close();
		  
	} catch (Exception e) {
		
		e.printStackTrace();
	}
	  

	}

	public void insertStudent(String methodname,Student student) {
		 try {
			  
			  String sql = methodMap.get(methodname);
			  String pattern = "\\$\\{[a-zA-Z]+\\}";
//			 创建 Pattern 对象
			  Pattern r = Pattern.compile(pattern);
			  // 现在创建 matcher 对象
			  Matcher m = r.matcher(sql);
			  
			  while (m.find()) {
				  System.out.println("Found value: " + m.group(0) );
				  Field fi = student.getClass().getDeclaredField(m.group(0).replace("${", "").replace("}", ""));
				  System.out.println("fi="+fi);
				  fi.setAccessible(true);
				  sql = sql.replace(m.group(0), "'"+fi.get(student)+"'");	  
			  }
			  System.out.println("ss="+sql);
			  PreparedStatement pst = conn.prepareStatement(sql);
			  int dd= pst.executeUpdate();
			  System.out.println("dd="+dd);
			  pst.close();
			  
		} catch (Exception e) {
			
			e.printStackTrace();
		}

	}

	public List<Student> selectStudentById(String methodname,String id) {
		
		 List<Student> studentList = new ArrayList<Student>();
		 try {
			  
			  String sql = methodMap.get(methodname);
			  String pattern = "\\$\\{[a-zA-Z]+\\}";
//			 创建 Pattern 对象
			  Pattern r = Pattern.compile(pattern);
			  // 现在创建 matcher 对象
			  Matcher m = r.matcher(sql);
			  while (m.find()) {
				  System.out.println("Found value: " + m.group(0) );
				  sql = sql.replace(m.group(0), "?");
				  
			  }
			  System.out.println("ss="+sql);
			  PreparedStatement pst = conn.prepareStatement(sql);
			  pst.setString(1, id);
			  pst.execute();
			  ResultSet rs =pst.getResultSet();
			  
			  
	          while(rs.next())
	          {
	        	 Student s = new Student();
	        	 Class student = s.getClass();
	        	 Field[] fileds = student.getDeclaredFields();
	        	 for(int k =0;k<fileds.length;k++){
	        		 Field ff = fileds[k];
	        		 ff.setAccessible(true);
	        		 ff.set(s, rs.getString(ff.getName()));
	        	 }
	        	 studentList.add(s);
	         }

			 pst.close();
			  
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
		return studentList;
	}

	public void updateStudent(String methodname,Student student) {
		 try {
			  
			  String sql = methodMap.get(methodname);
			  String pattern = "\\$\\{[a-zA-Z]+\\}";
//			 创建 Pattern 对象
			  Pattern r = Pattern.compile(pattern);
			  // 现在创建 matcher 对象
			  Matcher m = r.matcher(sql);
			  
			  while (m.find()) {
				  System.out.println("Found value: " + m.group(0) );
				  Field fi = student.getClass().getDeclaredField(m.group(0).replace("${", "").replace("}", ""));
				  System.out.println("fi="+fi);
				  fi.setAccessible(true);
				  sql = sql.replace(m.group(0), "'"+fi.get(student)+"'");	  
			  }
			  System.out.println("ss="+sql);
			  PreparedStatement pst = conn.prepareStatement(sql);
			  int dd= pst.executeUpdate();
			  System.out.println("dd="+dd);
			  pst.close();
			  
		} catch (Exception e) {
			
			e.printStackTrace();
		}

	}


}
